package com.xgr.wonderful.db;

import com.xgr.wonderful.constant.Constant;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 只有创建得到db 与clodeDB的方法
 * @author lsj
 *
 */
public class DBOpenHelper extends SQLiteOpenHelper {
	
	private static String CONVERSATION_TABLE_CREATE = "CREATE TABLE " +
			Constant.CONVERSATION_TABLE_NAME + "(" +
			Constant.CONVERSATION_REMOTE_USER_ID + " INTEGER PRIMARY KEY, " +
			Constant.CONVERSATION_REMOTE_USER_NAME + " TEXT, " +
			Constant.CONVERSATION_REMOTE_USER_PHOTO_BIG_URL + " TEXT, " +
			Constant.CONVERSATION_REMOTE_USER_PHOTO_SMALL_URL + " TEXT" + ");";
	
	private static DBOpenHelper singletonDbOpenHelper = null;

	private DBOpenHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}
	
	public static DBOpenHelper getInstance(Context context) {
		if (singletonDbOpenHelper == null) {
			syncInit(context) ;
		}
		return singletonDbOpenHelper;
	}
	
	private static synchronized void syncInit (Context context){
		if (singletonDbOpenHelper == null){
			singletonDbOpenHelper  = new DBOpenHelper(context, 
					Constant.DB_NAME, null, Constant.DB_VERSION) ;
		}
	}
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL(CONVERSATION_TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}
	
	public void closeDB() {
		if (singletonDbOpenHelper != null) {
	        try {
	            SQLiteDatabase db = singletonDbOpenHelper.getWritableDatabase();
	            db.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        singletonDbOpenHelper = null;
	    }
	}

}
